


from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse,redirect
import re
from rbac.models import Permission

class PermissionMiddleWare(MiddlewareMixin):

    def process_request(self,request):
        print("permission_list",request.session.get("permission_list"))
        current_path = request.path

        # 设置白名单放行
        for reg in  ["/login/","/admin/*"]:
            ret=re.search(reg,current_path)
            if ret:
                return None
        # /customers/edit/1

        # 校验是否登录

        user_id=request.session.get("user_id")
        if not user_id:
            return redirect("/login/")

        # 校验权限
        permission_list=request.session.get("permission_list")
        '''
        permission_list = [
        {"url":"","pid":""...}]
        '''

        # 路径导航列表
        request.breadcrumb = [
            {
            "title":"首页",
            "url": "/",
            },
        ]
        for item in permission_list:
             reg="^%s$"%item["url"]
             ret=re.search(reg,current_path)
             if ret:
                 show_id = item["pid"] or item["id"]    # pid有就取pid，没有就取id
                 request.show_id = show_id

                 # 确定面包屑列表
                 if item["pid"]:    # 有父权限
                     ppermission = Permission.objects.filter(pk=item["pid"]).first()   # 父权限
                     print("ppermission:",ppermission)
                     request.breadcrumb.extend(
                         [{
                             "title":ppermission.title,
                             "url": ppermission.url,

                         }, # 父权限
                         {
                             "title":item["title"],
                             "url": request.path,

                         }, # 子权限
                     ])
                 else:  # 没有父权限
                     request.breadcrumb.append(
                         {
                             "title":item["title"],
                             "url":item["url"]
                         }
                     )


                 return None

        return HttpResponse("无访问权限！")

